import { childrenUsers,teacherUSers } from '../public/list'
// 引入mock 生成数据
import Mock from 'mockjs'
let verificationCode: string
let expirationTime: number
// 创建注册接口
Mock.mock('/admin', 'post', (options) => {
    const { username, password, code,phone,name } = JSON.parse(options.body)
    const userExists = childrenUsers.some(user => user.username === username && user.password === password)
    // 验证当前的账户有没有 
    if (userExists) {
        return Mock.mock({
            code: 109,
            message: '用户名已存在',
        })
    } else if (username === '' || password === '' || phone === '' || name === '') {
        return Mock.mock({
            code: 107,
            message: '内容不能为空',
        })
    } else {
        // 注册
        const newUser = { username, password, phone,name }
        if(newUser.username.startsWith('XS')){
            childrenUsers.push(newUser)
        } else if (newUser.username.startsWith('JS')){
            teacherUSers.push(newUser)
        } else {
            return Mock.mock({
                code: 108,
                message: '账号格式不正确',
            })
        }
        return Mock.mock({
            code: 200,
            message: '注册成功',
        })
    }
})
// 发送验证码
Mock.mock('/sendCode', 'post', (options) => {
    const { phone } = JSON.parse(options.body)
    if (phone) {
        // 生成一个随机的4位数验证码
        verificationCode = Mock.mock('@string("0123456789", 4)')
        // 记录验证码的生成时间
        expirationTime = Date.now() + 60 * 1000 // 当前时间 + 1分钟
        return Mock.mock({
            verificationCode,
            expirationTime,
            code: 200,
            message: '验证码已发送',
        })
    } else {
        return Mock.mock({
            code: 100,
            message: '手机号不能为空'
        })
    }
})
// 验证验证码
Mock.mock('/verify', 'post', (options) => {
    const { code } = JSON.parse(options.body)
    // console.log(code)
    // 检查验证码是否存在并且未过期
    if (verificationCode && Date.now() <= expirationTime) {
        if (code === verificationCode) {
            return Mock.mock({
                code: 200,
                message: '验证码验证通过',
            });
        } else {
            return Mock.mock({
                code: 101,
                message: '验证码错误',
            });
        }
    } else {
        return Mock.mock({
            code: 110,
            message: '验证码已过期',
        })
    }
})
